package com.server.controler;

import com.server.util.ConfigUtil;
import com.server.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("server")
public class ServerC {
    public static Map<String, String> map = new HashMap<>();

    @RequestMapping("login")
    public String main(String userName, String passWord, String redirectUrl, HttpSession session, Model model) {
        if (StringUtil.isNotBlank(userName) && StringUtil.isNotBlank(passWord) && StringUtil.isNotBlank(redirectUrl)) {
            if (userName.equals(ConfigUtil.USERNAME) && passWord.equals(ConfigUtil.PASSWORD)) {
                //账号密码匹配
                String token = StringUtil.getUUID();
                //创建全局会话，将令牌信息放入会话
                session.setAttribute("token", token);
                //把令牌信息放入缓存
                ConfigUtil.T_TOKEN.add(token);
                //重定向到请求路径，带上token
//                model.addAttribute("token", token);
                return "redirect:"+  redirectUrl+"?token="+token;
            }
        }
        //如果账号密码错误，重新到登录界面,并将请求路径带上
        model.addAttribute("redirectUrl", redirectUrl);
        return "serverLogin";
    }

    /**
     * @return void
     * @Author qzl
     * @Description 校验token有效性
     * @Date 2019/10/26 12:27
     * @Param [userName, passWord, toUrl, response]
     **/
    @RequestMapping("checkTicket")
    @ResponseBody
    public String checkTicket(String token) {
        if (StringUtil.isNotBlank(token)) {
            boolean contains = ConfigUtil.T_TOKEN.contains(token);
            //token有效
            if (contains){
                return "true";
            }
        }
        return "false";
    }

    /**
     * 校验是否登录
     *
     * @param
     * @return
     */
    @RequestMapping("getTicket")
    public String getTicket(String redirectUrl, HttpSession session, Model model) {
        //是否有全局的对话信息
        String token = (String) session.getAttribute("token");
        if (StringUtil.isBlank(token)) {//没有全局会话
            //跳转到统一认证中心登录界面
            model.addAttribute("redirectUrl", redirectUrl);
            return "serverLogin";
        }else{
            //有全局会话，取出令牌到跳转地址
            boolean contains = ConfigUtil.T_TOKEN.contains(token);
            if (contains){
//                model.addAttribute("token", token);
                return "redirect:" +  redirectUrl+"?token="+token;
            }
            //查不到全局会话
            model.addAttribute("redirectUrl", redirectUrl);
            return "serverLogin";
        }
    }
}
